package wujinye.com.controller.view;

import wujinye.com.controller.BaseServlet;
import wujinye.com.model.Article;
import wujinye.com.model.Conference;
import wujinye.com.model.Dept;
import wujinye.com.service.ArticleService;
import wujinye.com.service.DeptService;
import wujinye.com.service.MeetService;
import wujinye.com.service.UserService;
import wujinye.com.service.impl.ArticleServiceImpl;
import wujinye.com.service.impl.DeptServiceImpl;
import wujinye.com.service.impl.MeetServiceImpl;
import wujinye.com.service.impl.UserServiceImpl;
import wujinye.com.utils.DateUtil;
import wujinye.com.utils.PageUtil;
import wujinye.com.utils.StrUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@WebServlet("/view/*")
public class UIServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    private DeptService deptService = new DeptServiceImpl();

    private ArticleService articleService = new ArticleServiceImpl();

    private MeetService meetService = new MeetServiceImpl();

    // loginservlet的跳转

    // 返回登录页面index.jsp
    public void index(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.getRequestDispatcher(req.getContextPath() + "/index.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 登录进入home页面
    public void gohome(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.getRequestDispatcher(req.getContextPath() + "/html/home.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 登录时密码或者用户名错误，返回登录界面，并提示消息
    public void reindex(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.getRequestDispatcher(req.getContextPath() + "/index.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        req.getSession().removeAttribute("logmsg");
    }

    // 进入注册页面
    // 注册填写的信息数据有误，点击注册时返回注册界面，并提示信息
    public void register(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.getRequestDispatcher(req.getContextPath() + "/register.jsp").forward(req, resp);
            req.getSession().removeAttribute("regmsg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 进入忘记密码的页面
    // 填写信息有误时，提示错误信息
    public void forget(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.getRequestDispatcher(req.getContextPath() + "/forget.jsp").forward(req, resp);
            req.getSession().removeAttribute("forgetmsg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // userservlet的跳转/跳转user的页面
    // 跳转至用户详细信息的页面（user_look.jsp）
    public void userLook(HttpServletRequest req, HttpServletResponse resp) {

        try {
            String uId = req.getParameter("uId");
            // 从数据库获取用户的详细资料
            Map<String, Object> userDetail = userService.findUserDetail(Integer.parseInt(uId));
            // 从数据库查找部门ID和部门名称
            List<Dept> allDept = deptService.findAllDept();
            req.setAttribute("detailInfo", userDetail);
            req.setAttribute("deptList", allDept);
            req.getRequestDispatcher(req.getContextPath() + "/html/user_look.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 跳转至user.jsp页面，以及查找数据后刷新页面
    public void userList(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String search = req.getParameter("search");
            String currentPage = req.getParameter("page");
            if (StrUtil.checkString(search)) {
                search = URLDecoder.decode(search, "UTF-8");
                byte[] bytes = search.getBytes("ISO-8859-1");
                search = new String(bytes, "UTF-8");
            }
            int page = 1;
            if (StrUtil.checkString(currentPage)) {
                page = Integer.parseInt(currentPage);
            }
            String userId = req.getSession().getAttribute("userId").toString();
            List<Map<String, Object>> list = userService.findUserList(Integer.parseInt(userId), search, page);
            req.setAttribute("userList", list);
            long totalPage = PageUtil.getTotalUserPage(userService.getTotalCount(search));
            long startPage = PageUtil.getStartPage(page) + 1;
            long endPage = PageUtil.getEndPage(totalPage, page);
            req.setAttribute("totalPage", totalPage);
            req.setAttribute("startPage", startPage);
            req.setAttribute("endPage", endPage);
            req.setAttribute("currentPage", page);
            req.setAttribute("search", search);
            req.getRequestDispatcher(req.getContextPath() + "/html/user.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 跳转至user_detail.jsp页面
    // 被查看的用户look值+1
    public void userDetail(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String uId = req.getParameter("uId");
            // 从数据库获取用户的详细资料
            Map<String, Object> userDetail = userService.findUserDetail(Integer.parseInt(uId));

            // 查看次数+1
            String look = userDetail.get("look").toString();
            Integer lookCount = 0;
            if (StrUtil.checkString(look)) {
                lookCount = StrUtil.stringToInteger(look) + 1;
            }
            userDetail.put("look", lookCount);
            req.setAttribute("detailInfo", userDetail);
            userService.lookCount(StrUtil.stringToInteger(uId), lookCount);
            req.getRequestDispatcher(req.getContextPath() + "/html/user_detail.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 跳转至my_user.jsp页面
    public void myFocusList(HttpServletRequest req, HttpServletResponse resp) {

        try {
            String currentPage = req.getParameter("page");
            String ufId = req.getParameter("ufId");
            String userId = req.getSession().getAttribute("userId").toString();
            int page = 1;
            if (StrUtil.checkString(currentPage)) {
                page = Integer.parseInt(currentPage);
            }
            // 如果有ufId表示点击了取消关注
            if (StrUtil.checkString(ufId)) {
                // 取关操作
                userService.removeFocus(StrUtil.stringToInteger(userId), StrUtil.stringToInteger(ufId));
            }
            // 获取用户的关注列表
            List<Map<String, Object>> focusList = userService.findFocusList(StrUtil.stringToInteger(userId), page);
            long totalPage = PageUtil.getTotalUserPage(userService.getFocusTotalCount(StrUtil.stringToInteger(userId)));
            long startPage = PageUtil.getStartPage(page) + 1;
            long endPage = PageUtil.getEndPage(totalPage, page);
            req.setAttribute("totalPage", totalPage);
            req.setAttribute("startPage", startPage);
            req.setAttribute("endPage", endPage);
            req.setAttribute("currentPage", page);
            req.setAttribute("focusList", focusList);
            req.getRequestDispatcher(req.getContextPath() + "/html/my_user.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 如果uId为空，则跳转至article.jsp页面
    // 如果uId不为空，则跳转至article_collect.jsp页面
    public void showArticle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String currentPage = req.getParameter("page");
            String search = req.getParameter("search");
            String uId = req.getParameter("uId");
            if (StrUtil.checkString(search)) {
                search = URLDecoder.decode(search, "UTF-8");
                byte[] bytes = search.getBytes("ISO-8859-1");
                search = new String(bytes, "UTF-8");
            }
            int page = 1;
            if (StrUtil.checkString(currentPage)) {
                page = Integer.parseInt(currentPage);
            }
            List<Map<String, Object>> articleList = null;
            long totalPage = 0L;
            if (StrUtil.checkString(uId)) {
                String userId = req.getSession().getAttribute("userId").toString();
                articleList = articleService.findArticleList(search, page, StrUtil.stringToInteger(userId));
                totalPage = PageUtil.getTotalArticlePage(articleService.getTotalArticle(search, StrUtil.stringToInteger(userId)));
            } else {
                articleList = articleService.findArticleList(search, page, null);
                totalPage = PageUtil.getTotalArticlePage(articleService.getTotalArticle(search, null));
            }
            req.setAttribute("articleList", articleList);
            long startPage = PageUtil.getStartPage(page) + 1;
            long endPage = PageUtil.getEndPage(totalPage, page);
            req.setAttribute("totalPage", totalPage);
            req.setAttribute("startPage", startPage);
            req.setAttribute("endPage", endPage);
            req.setAttribute("currentPage", page);
            req.setAttribute("search", search);
            if (StrUtil.checkString(uId)) {
                req.getRequestDispatcher(req.getContextPath() + "/html/article_collect.jsp").forward(req, resp);
                return;
            } else {
                req.getRequestDispatcher(req.getContextPath() + "/html/article.jsp").forward(req, resp);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 跳转至article_detail.jsp页面
    public void articleDetail(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String aId = req.getParameter("aId");
            String userId = req.getSession().getAttribute("userId").toString();
            int id = 1;
            if (StrUtil.checkString(aId)) {
                id = StrUtil.stringToInteger(aId);
            }
            articleService.addViews(id);
            // 获取文章信息
            Map<String, Object> articleMap = articleService.findArticleById(id);
            // 获取既是我关注的人而且收藏文章的用户姓名
            List<Map<String, Object>> collectList = articleService.findCollectList(StrUtil.stringToInteger(userId), id);
            // 查看登录用户是否收藏文章
            String collect = articleService.isCollect(StrUtil.stringToInteger(userId), id);
            req.setAttribute("collect", collect);
            req.setAttribute("collectList", collectList);
            req.setAttribute("article", articleMap);
            req.getRequestDispatcher(req.getContextPath() + "/html/article_detail.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 跳转至article_add.jsp页面
    public void writeArticle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.getRequestDispatcher(req.getContextPath() + "/html/article_add.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        req.getSession().removeAttribute("releasemsg");
    }

    // 跳转至department.jsp页面
    public void showDepartmentList(HttpServletRequest req, HttpServletResponse resp) {
        try {
            List<Map<String, Object>> userDeptList = userService.findUserDeptList();
            List<Map<String, Object>> userCount = userService.getUserCount();
            req.setAttribute("userCount", userCount);
            req.setAttribute("userDeptList", userDeptList);
            req.getRequestDispatcher(req.getContextPath() + "/html/department.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 跳转至meeting.jsp页面
    public void showMeetList(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String search = req.getParameter("search");
            String currentPage = req.getParameter("page");
            String deptName = req.getParameter("deptName");
            int page = 1;
            if (StrUtil.checkString(currentPage)) {
                page = StrUtil.stringToInteger(currentPage);
            }
            if (StrUtil.checkString(search)) {
                search = URLDecoder.decode(search, "UTF-8");
                byte[] bytes = search.getBytes("ISO-8859-1");
                search = new String(bytes, "UTF-8");
            }
            if (StrUtil.checkString(deptName)) {
                deptName = URLDecoder.decode(deptName, "UTF-8");
                byte[] bytes = deptName.getBytes("ISO-8859-1");
                deptName = new String(bytes, "UTF-8");
            }
            List<Conference> meetingList = meetService.findMeetingList(search, deptName, page);
            List<Dept> allDept = deptService.findAllDept();
            long totalPage = PageUtil.getTotalMeetingPage(meetService.getTotalMeetings(search, deptName));
            long startPage = PageUtil.getStartPage(page) + 1;
            long endPage = PageUtil.getEndPage(totalPage, page);
            req.setAttribute("meetingList", meetingList);
            req.setAttribute("totalPage", totalPage);
            req.setAttribute("startPage", startPage);
            req.setAttribute("endPage", endPage);
            req.setAttribute("currentPage", page);
            req.setAttribute("search", search);
            req.setAttribute("deptName",deptName);
            req.setAttribute("deptList",allDept);
            req.getRequestDispatcher(req.getContextPath()+"/html/meeting.jsp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 跳转至meeting_detail.jsp页面
    public void meetingDetail(HttpServletRequest req,HttpServletResponse resp){
        try {
            String mId = req.getParameter("mId");
            String userId = req.getSession().getAttribute("userId").toString();
            if (StrUtil.checkString(mId)){
                Conference meeting = meetService.findMeetingById(StrUtil.stringToInteger(mId));
                long totalPerson = 0L;
                long totalAbsence = 0L;
                Object[] isCome = null;
                if (meeting.getStatus() != 3){
                    totalPerson = meetService.getTotalPerson(StrUtil.stringToInteger(mId));
                    totalAbsence = meetService.getTotalAbsence(StrUtil.stringToInteger(mId));
                    if (!StrUtil.stringToInteger(userId).equals(meeting.getUserId())){
                        //System.out.println(111);
                        // isCome为null则无关，isCome[0]=0则未参加，isCome[0]=1则已参加
                        isCome = meetService.isCome(StrUtil.stringToInteger(userId),StrUtil.stringToInteger(mId));
                    }
                }
                req.setAttribute("meeting",meeting);
                req.setAttribute("totalPerson",totalPerson);
                req.setAttribute("absence",totalAbsence);
                req.setAttribute("uId",userId);
                req.setAttribute("isCome",isCome);
                req.getRequestDispatcher(req.getContextPath()+"/html/meeting_detail.jsp").forward(req,resp);
            }else {
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 跳转至meeting_add.jsp页面
    public void writeMeeting(HttpServletRequest req,HttpServletResponse resp){
        try{
            List<Dept> depts = deptService.findAllDept();
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
            Date currentTime = new Date();
            String minTime = formatter.format(currentTime);
            req.setAttribute("minTime",minTime);
            req.setAttribute("deptList",depts);
            req.getRequestDispatcher(req.getContextPath()+"/html/meeting_add.jsp").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
        req.getSession().removeAttribute("meetingmsg");
    }
}
